package com.bdqn.util;
/*
 * 获取资源
 * 释放资源
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcUtil {

	//加载数据库驱动
	static {
		try {
			Class.forName(PropertiesUtil.getProperty(KeyConstants.MYSQL_DRIVER_PATH_KEY));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		//获取连接
		//先声明connection变量，再通过DriverManager给connection赋值，最后返回conne
		Connection connection=null;
		try {
			connection=DriverManager.getConnection(PropertiesUtil.getProperty(KeyConstants.DB_SERVER_URL_KEY), PropertiesUtil.getProperty(KeyConstants.DB_SERVER_USER_KEY), PropertiesUtil.getProperty(KeyConstants.DB_SERVER_PASSWORD));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	//不操作数据库时候，释放资源
	//可变参数--AutoCloseable...autoCloseables:没有参数或有一个参数或有多个参数
	public static void close(AutoCloseable...autoCloseables) {
		try {
			//判断是否为空且长度大于0
			if(autoCloseables!=null && autoCloseables.length>0) {
				//循环遍历autoCloseables，判断是否为空，并且将资源关闭
				for (AutoCloseable autoCloseable : autoCloseables) {
					if(autoCloseable!=null) {
						autoCloseable.close();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
